package 密码学实验;

public class RC4Cipher {
    private int[] s = new int[256];
    private int x, y;

    public RC4Cipher(String key) {
        // KSA密钥调度算法
        int[] t = new int[256];
        for (int i = 0; i < 256; i++) {
            s[i] = i;
            t[i] = key.charAt(i % key.length());
        }

        int j = 0;
        for (int i = 0; i < 256; i++) {
            j = (j + s[i] + t[i]) % 256;
            swap(i, j);
        }
    }

    private void swap(int i, int j) {
        int temp = s[i];
        s[i] = s[j];
        s[j] = temp;
    }

    public String process(String input) {
        x = 0;
        y = 0;
        char[] output = new char[input.length()];

        for (int i = 0; i < input.length(); i++) {
            output[i] = (char)(input.charAt(i) ^ keyStream());
        }
        return new String(output);
    }

    private int keyStream() {
        x = (x + 1) % 256;
        y = (y + s[x]) % 256;
        swap(x, y);
        return s[(s[x] + s[y]) % 256];
    }

    public static void main(String[] args) {
        RC4Cipher rc4 = new RC4Cipher("StrongKey!");
        String text = "RC4 Encryption";

        String encrypted = rc4.process(text);
        String decrypted = rc4.process(encrypted);

        System.out.println("原始: " + text);
        System.out.println("加密: " + encrypted);
        System.out.println("解密: " + decrypted);
    }
}